import {withLoading} from 'utils/dva';
import * as routerRedux from 'react-router-redux';
import pathToRegexp from 'path-to-regexp';
import services from '../../services';
import model from '../model';

export default model.extend({

  namespace: 'picCreate',

  state: {
    record: {},
    id: '',
    loading: {
      create: false,
      detail: false
    }
  },

  subscriptions: {
    setup({dispatch, history}) {
      // 监听路由的变化，请求页面数据
      return history.listen(({pathname}) => {
        const params = pathToRegexp('/pic/create/:id').exec(pathname);
        if (params) {
          const id = params[1];
          dispatch({type: 'updateState', payload: {id, record: {}}});
          dispatch({type: 'getDetail'});
        } else {
          dispatch({type: 'updateState', payload: {id: '', record: {}}});
        }
      });
    }
  },

  effects: {
    * add({payload}, {call, put}) {
      yield call(withLoading(services.pic.add, 'create', '新增成功'),
          {...payload});
      yield put(routerRedux.push('/pic/list'));
    },
    * edit({payload}, {select, call, put}) {
      const {id} = yield select(({ picCreate }) => picCreate);
      yield call(withLoading(services.pic.edit, 'create', '更新成功'),
          {...payload, id});
      yield put(routerRedux.push('/pic/list'));
    },
    * getDetail({ payload }, {select, call, update}) {
      const { id } = yield select(({ picCreate }) => picCreate);
      const { data } = yield call(withLoading(services.pic.getDetail,
          'detail', ), {id, ...payload});
      yield update({
        record: data
      });
    }
  },

  reducers: {
  }

});
